<?php

/**
 * Part of the Fuel framework.
 *
 * @package Fuel
 * @version 1.0
 * @author Fuel Development Team
 * @license MIT License
 * @copyright 2010 - 2012 Fuel Development Team
 * @link http://fuelphp.com
 */

/**
 * Template Controller class
 *
 * A base controller for easily creating templated output.
 *
 * @package Fuel
 * @category Core
 * @author tien.tran@sgame.vn
 */

use Fuel\Core\Response;
use Fuel\Core\Cookie;
use Fuel\Core\Log;

abstract class Controller_Hybrid extends Controller_Rest
{

    public $auto_render = true;

    /**
     *
     * @var string page template
     */
    public $template = 'new_template';
    
    /**
     *
     * @var bool return as controller rest
     */
    public $rest = false;

    /**
     * Check return result as rest controller or template controller
     *
     * @return boolean
     */
    public function is_rest ()
    {
        if ($this->rest == TRUE)
            return true;
        
        return \Fuel\Core\Input::is_ajax();
    }

    /**
     * Load the template and create the $this->template object
     */
    public function before ($template = null)
    {
        
        if (! is_null($template)) {
            $this->template = $template;
        }
        
        if (! $this->is_rest()) {
            if (! empty($this->template) and is_string($this->template)) {
                // Load the template
                $this->template = \View::forge($this->template);
            }
        }
        
        return parent::before();
    }

    /**
     * After controller method has run output the template
     *
     * @param Response $response            
     */
    public function after ($response)
    {
        if (! $this->is_rest()) {
            // If nothing was returned default to the template
            if (empty($response)) {
                $response = $this->template;
            }
            
            // If the response isn't a Response object, embed in the available
            // one for BC
            // @deprecated can be removed when $this->response is removed
            if (! $response instanceof Response) {
                $this->response->body = $response;
                $response = $this->response;
            }
        }
        
        // clear rest
        $this->rest = FALSE;
        
        return parent::after($response);
    }

    /**
     * router
     *
     * requests are not made to methods directly The request will be for an
     * "object".
     * this simply maps the object and method to the correct Controller method.
     *
     * this router will call action methods for normal requests,
     * and REST methods for RESTful calls
     *
     * @param
     *            string
     * @param
     *            array
     */
    public function router ($resource, array $arguments)
    {
        
        // if this is an ajax call
        if ($this->is_rest()) {
            // have the Controller_Rest router deal with it
            return parent::router($resource, $arguments);
        }
        
        // check if the action method exists
        if (method_exists($this, 'action_' . $resource)) {
            // if so, call the action
            return call_user_func_array(array(
                    $this,
                    'action_' . $resource
            ), $arguments);
        }
        
        // if not, we got ourselfs a genuine 404!
        throw new \HttpNotFoundException();
    }

    public static $template_holder = array();

    public function _assign ($name, $value)
    {
        // add value
        self::$template_holder[$name][] = $value;
    }

    protected function build_header_and_footer ($count_notif = TRUE)
    {
        Module::load('slayout');
        Lang::load('slayout::header.ini', 'friend_request');
        $time = microtime(TRUE);
        $count_friend_req = \Model_Friend::count_unread_friend_request(SUser::singleton()->user_id);
        if ($count_notif) {
            $count_notif = \Model_Notification::count_unread_notif(SUser::singleton()->user_id);
        } else {
            $count_notif = 0;
        }
        Log::debug('TIME COUNT UNREAD FRIEND && NOTIF = '. (microtime(TRUE) - $time));
        $friend_request = \Model_Friend::list_friendrequest(\SUser::singleton()->user_id, 6);
        
        $time = microtime(TRUE);
        $level = \Model_Level::get_2_level(SUser::singleton()->user_social_exp);
        $next_2_level = \Model_Level::get_next_2_level(SUser::singleton()->user_social_exp);
        $broadcast = \Model_Broadcast::get_active();
        $non_cooked = array();
        if (count($broadcast) > 0) {
            foreach ($broadcast as $b) {
                if (! Cookie::get('broadcast_' . $b['_id']->__toString())) {
                    $non_cooked[] = $b;
                }
            }
        }
        
        Log::debug('TIME get broadcast & level = '. (microtime(TRUE) - $time));
        
//        $time = microtime(TRUE);
//        $notifications = \Model_Notification::get_notifications(\SUser::singleton()->user_id, 0, 5, FALSE);
//        Log::debug('TIME get notifs in header = '. (microtime(TRUE) - $time));
        
        $time = microtime(TRUE);
//        $users = array();
//        if (count($notifications) > 0) {
//            $user_ids = array();
//            foreach ($notifications as $notif) {
//                $user_ids[] = $notif['notification_sender_uid'];
//            }
//            $users = \Model_User::get_users($user_ids);
//        }
        Log::debug('TIME get user notifs in header = '. (microtime(TRUE) - $time));
        $this->_assign('header', \View::forge('header')->set('count_notif', $count_notif)
            ->set('count_friend_req', $count_friend_req)
            ->set('user', SUser::singleton())
            ->set('level', $level)
            ->set('non_cooked', $non_cooked)
            ->set('next_2_level', $next_2_level)
            ->set('friend_request', $friend_request));
            //->set('notifications', $notifications)
          //  ->set('notif_users', $users));
        
        \View::set_global('header', implode('', self::$template_holder['header']));
        \View::set_global('footer', \View::forge('footer'));
    }

    protected function build_left_column ($being_viewed_user = NULL)
    {
        $being_viewed_user_info = array();
        if ($being_viewed_user) {
            $being_viewed_user_info = \Model_User::get(array(
                    'user_id' => (int) $being_viewed_user
            ));
        } else {
            $being_viewed_user_info = SUser::singleton()->get();
        }
        $this->_assign('left', \View::forge('new_left_nav')->set("being_viewed_uid", $being_viewed_user)
            ->set("being_viewed_user", $being_viewed_user_info));
        \View::set_global('left', implode('', self::$template_holder['left']));
        return $being_viewed_user_info;
    }

    protected function build_right_column ($user_id)
    {
        $this->_assign('right', \View::forge('suser::profile/right_action'));
        $time = microtime(TRUE);
        $quests = \Model_Quest::recommend_quests($user_id);
        Log::debug("TIME recommed quest = " . (microtime(TRUE) - $time));
        
        $this->_assign('right', \View::forge('suser::profile/right_quest')->set('quests', $quests['data'])
            ->set('flag', $quests['flag']));
        
        $time = microtime(TRUE);
        $recommended = \Model_Friend::recommend_friend($user_id);
        Log::debug("TIME recommend friend = " . (microtime(TRUE) - $time));
        
        $this->_assign('right', \View::forge('suser::profile/right_friend')->set('recommended', $recommended));
        
        //$time = microtime(TRUE);
        //$get_famous_user = \Model_User::get_user_famous();
        //$get_libcontent = \Model_Library::getLibUserFamous($get_famous_user);
        //Log::debug("TIME get famous = " . (microtime(TRUE) - $time));
        
        //$this->_assign('right', \View::forge('suser::profile/right_member')->set('user_famous', $get_libcontent));
        
        
        $toplevel = \Model_User::TopUserLevel();
        
        $time = microtime(TRUE);
        $topMoney = \Model_User::TopUserMoney();
        Log::debug("TIME get top money = " . (microtime(TRUE) - $time));
        
        //$time = microtime(TRUE);
        //$topMentor = \Model_User::TopUserMentor();
        //Log::debug("TIME get top mentor = " . (microtime(TRUE) - $time));
        
        $this->_assign('right', \View::forge('suser::profile/right_famous')->set('topLevel', $toplevel)
            ->set('topMoney', $topMoney));
            //->set('topMentor', $topMentor));
        \View::set_global('right', implode('', self::$template_holder['right']));
    }

    protected function build_right_column_friendlist ($user_id)
    {
        $this->_assign('right', \View::forge('suser::profile/right_action'));
        // $quests = \Model_Quest::recommend_quests($user_id);
        // $this->_assign('right', \View::forge('suser::profile/right_quest')->set('quests', $quests));
        $recommended = \Model_Friend::recommend_friend($user_id);
        $this->_assign('right', \View::forge('suser::profile/right_friend')->set('recommended', $recommended));
        $get_famous_user = \Model_User::get_user_famous();
        $get_libcontent = \Model_Library::getLibUserFamous($get_famous_user);
        
        $this->_assign('right', \View::forge('suser::profile/right_member')->set('user_famous', $get_libcontent));
        \View::set_global('right', implode('', self::$template_holder['right']));
    }

    protected function build_right_column_note ($user_id)
    {
        $NotesRelated = \Model_Notes::NotesRelatedToMe($user_id);
        $this->_assign('right', \View::forge('snotes::right_note')->set('notesRelated', $NotesRelated));
        
        // $this->template->right = implode('', self::$template_holder['right']);
        
        \View::set_global('right', implode('', self::$template_holder['right']));
    }
    
    // protected function build_left_column_quest ($being_viewed_user = NULL, $counter)
    // {
    // $this->_assign('left', \View::forge('feed/left_info'));
    // $this->_assign('left', \View::forge('squest::left_quest')->set("counter", $counter));
    // $this->_assign('left', \View::forge('feed/left_like')->set("profile_id", $being_viewed_user));
    // // $this->_assign('left', \View::forge('feed/left_app'));
    // $this->template->left = implode('', self::$template_holder['left']);
    // }
    protected function build_right_column_quest ($all_quest = array(), $counter = array())
    {
        $this->_assign('right', \View::forge('squest::right_quest')->set("quests", $all_quest)
            ->set('counter', $counter)
            ->set('user_id', SUser::singleton()->user_id));
        $this->template->right = implode('', self::$template_holder['right']);
        \View::set_global('right', implode('', self::$template_holder['right']));
    }

    public function action_edit ()
    {
        $part = \Uri::segment(3);
        $this->template = "tpl_twocolumn";
        $this->before();
        
        $user = $this->getUserLogged();
        if (! $user) {
            Response::redirect('login/sgame');
        }
        
        if (\Input::post()) {
            \Model_User::update_info($user['user_id'], $part, \Input::post());
        }
        
        $user = \Model_User::get_user($user['user_id']);
        
        \Sgame\Lang::load('suser::friend.ini', 'friend', 'vi');
        \Sgame\Lang::load('suser::profile.ini', 'profile', 'vi');
        
        $this->build_header_and_footer();
        $this->build_left_column_edit($part);
        
        $this->template->title = "Edit Profile";
        
        $this->template->content = \View::forge('profile/edit')->set('editing_part', $part)
            ->set('editing_user', $user)
            ->set('is_feed', TRUE);
    }

    protected function build_left_column_edit ($part)
    {
        $this->_assign('left', \View::forge('profile/edit/left_column')->set('editing_part', $part));
        $this->template->left = implode('', self::$template_holder['left']);
    }

    public function action_autocomplete_game ()
    {
        $this->template = '';
        $term = \Input::get('term');
        $data = \Model_User::get_games($term);
        // echo JSON to page
        $response = $_GET["callback"] . "(" . json_encode($data) . ")";
        echo $response;
    }

    protected function build_column_topbar_library ($CatOption, $search_lib_text, $cat_info)
    {
        $this->_assign('topbar', \View::forge('slibrary::top_bar')->set('CatSelectOption', $CatOption)
            ->set('search_lib_text', $search_lib_text));
        $cib_id = Input::param('cid');
        $pib_id = Input::param('pid');
        $this->_assign('topbar', \View::forge('slibrary::left_library')->set('catinfo', $cat_info)
            ->set('getcatid', $cib_id)
            ->set('parentid', $pib_id));
        
        $this->template->topbar = implode('', self::$template_holder['topbar']);
    }

    protected function build_left_column_library ()
    {
        $this->template->left = '';
    }

    protected function build_right_column_library ($mostView)
    {
        // $this->_assign('right', \View::forge('slibrary::right_library'));
        $this->_assign('right', \View::forge('slibrary::right_library_mostview')->set('MostView', $mostView));
        $this->template->right = implode('', self::$template_holder['right']);
    }

    protected function build_new_left_column ($being_viewed_user = NULL)
    {
        // $this->_assign('left', \View::forge('feed/left_info'));
        // $this->_assign('left', \View::forge('feed/left_like')->set("profile_id", $being_viewed_user));
        // $this->_assign('left', \View::forge('feed/left_app'));
        $this->_assign('left', \View::forge('layout/left_bar')->set("profile_id", $being_viewed_user));
        \View::set_global('left', implode('', self::$template_holder['left']));
    }

    /**
     * build user top infomation of page _ include content
     *
     * @param int $user_social_exp            
     * @param int $viewer_id            
     * @param int $profile_id            
     */
    public function build_user_basic ($user_social_exp, $viewer_id, $profile_id)
    {
        \Module::load('sfriend');
        $level = \Model_Level::get_2_level($user_social_exp);
        $_relationship = \SFriend\Model_Friend::check_friendrelationship($viewer_id, $profile_id);
        
        $followAgain = FALSE;   
            $checkUnfollow = \Model_Neo4j::CheckUnfollowUser($viewer_id, $profile_id);
            if($checkUnfollow === FALSE){
                $followAgain = FALSE;
            }else{
                $followAgain = TRUE;
            }
     
        
        \View::set_global('user_basic', \View::forge('user/user_basic')->set('level', $level)
            ->set('_relationship', $_relationship)
            ->set('followAgain', $followAgain)
            ->set('game', \Model_User::get_pair_games()));
    }
    
    /**
     * 
     */
    protected function load_css_js() {
        $this->template->css = array (
            'main.css',
            'NewVersionMainStyle.css',
            'action.css',
            'ShowimagesBox.css'
        );
        
        $this->template->js = array (
            'plugins/jquery/jquery.1.7.2.min.js',
            'plugins/jquery/jquery.timeago.js',
            'plugins/jquery/jquery-ui-1.8.21.custom.min.js',
            'plugins/jquery/jquery.mCustomScrollbar.js',
            'plugins/jquery/jquery.mousewheel.min.js',
            'plugins/jquery/jquery.cookie.js',
            'site.js',
            'common.js',
            'feed.js',
            'post.js',
            'comment.js',
            'like.js',
            'friend.js',
            'css_browser_selector.js'
        );
    }
    protected function add_css($arr_css = array()) {
        if ($arr_css && is_array($arr_css)) {
            $this->template->css = array_merge($this->template->css, $arr_css);
        }
    }
    
    protected function replace_css($arr_css = array()) {
        if ($arr_css && is_array($arr_css)) {
            $this->template->css = $arr_css;
        }
    }
    
    protected function add_js($arr_js = array()) {
        if ($arr_js && is_array($arr_js)) {
            $this->template->js = array_merge($this->template->js, $arr_js);
        }
    }
    
    public function replace_js($arr_js = array()) {
        if ($arr_js && is_array($arr_js)) {
            $this->template->js = $arr_js;
        }
    }
} 


